package com.icode.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.icode.common.constant.OrderStatusEnum;
import com.icode.common.constant.WareConstant;
import com.icode.common.exception.NoStockException;
import com.icode.common.to.OrderTo;
import com.icode.common.to.SkuHasStockVo;
import com.icode.common.to.mq.StockDetailTo;
import com.icode.common.to.mq.StockLockedTo;
import com.icode.common.utils.R;
import com.icode.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.icode.gulimall.ware.entity.WareOrderTaskEntity;
import com.icode.gulimall.ware.feign.OrderFeignService;
import com.icode.gulimall.ware.feign.ProductFeignService;
import com.icode.gulimall.ware.service.WareOrderTaskDetailService;
import com.icode.gulimall.ware.service.WareOrderTaskService;
import com.icode.gulimall.ware.vo.MemberAddressVo;
import com.icode.gulimall.ware.vo.OrderItemVo;
import com.icode.gulimall.ware.vo.OrderVo;
import com.icode.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icode.common.utils.PageUtils;
import com.icode.common.utils.Query;

import com.icode.gulimall.ware.dao.WareSkuDao;
import com.icode.gulimall.ware.entity.WareSkuEntity;
import com.icode.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;


    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderFeignService orderFeignService;


    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * @param params skuId wareId
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }


    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1.判断如果还没有这个库存记录新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)) {
            //如果没有库存就插入一个
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);

            //远程查询sku的名字，如果失败整个事务无需回滚
            //1、自己catch异常
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> checkWareStockBySkuId(List<Long> skuIds) {

        List<SkuHasStockVo> resultList = skuIds.stream().map(skuId -> {
            Long count = this.baseMapper.queryStockBySkuId(skuId);
            SkuHasStockVo skuhasStockVo = new SkuHasStockVo();
            skuhasStockVo.setHasStock(count == null ? false : count > 0);
            skuhasStockVo.setSkuId(skuId);
            return skuhasStockVo;
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public Map<Long, Boolean> checkItemsStock(Map<String, String> skuIdInfo) {
        List<WareSkuEntity> entityList = wareSkuDao.selectBySkuIds(skuIdInfo.keySet());
        // todo 先假设商品都在一个厂库
        Map<Long, Boolean> booleanMap = entityList.stream()
                .collect(Collectors.toMap(WareSkuEntity::getSkuId, item -> {
                    Integer stock = item.getStock();
                    String skuId = item.getSkuId().toString();
                    Integer count = Integer.parseInt(skuIdInfo.get(skuId));
                    return stock >= count;
                }));
        return booleanMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean lockItemsStock(WareSkuLockVo lockVo) {
        MemberAddressVo memberAddressVo = lockVo.getMemberAddressVo();
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(lockVo.getOrderSn());
        orderTaskEntity.setConsignee(memberAddressVo.getName());
        orderTaskEntity.setConsigneeTel(memberAddressVo.getPhone());
        orderTaskEntity.setDeliveryAddress(memberAddressVo.getDetailAddress());
        orderTaskEntity.setOrderComment("");
        orderTaskEntity.setPaymentWay(1);
        orderTaskEntity.setTaskStatus(0);
        orderTaskEntity.setOrderBody("");
        orderTaskEntity.setCreateTime(new Date());
        orderTaskEntity.setWareId(1l);
        orderTaskEntity.setTaskComment("");
        wareOrderTaskService.save(orderTaskEntity);

        List<OrderItemVo> locks = lockVo.getLocks();
        //当前工作的Id
        Long taskId = orderTaskEntity.getId();
        // todo 先假设商品都在 仓库1
        for (OrderItemVo item : locks) {
            Long skuId = item.getSkuId();
            Integer count = item.getCount();
            //如果修改成功返回值是1，否则是0
            int affected_rows = wareSkuDao.lockStockBySkuId(skuId, count, 1);

            if (affected_rows == 1) {
                WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                detailEntity.setSkuId(skuId);
                detailEntity.setSkuName(item.getTitle());
                detailEntity.setSkuNum(item.getCount());
                detailEntity.setTaskId(taskId);
                detailEntity.setWareId(1l);
                detailEntity.setLockStatus(1);

                wareOrderTaskDetailService.save(detailEntity);

                StockDetailTo stockDetailTo = new StockDetailTo();
                BeanUtils.copyProperties(detailEntity, stockDetailTo);

                StockLockedTo stockLockedTo = new StockLockedTo();
                stockLockedTo.setId(taskId);
                stockLockedTo.setDetailTo(stockDetailTo);
                rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
            } else {
                //库存锁定异常
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo stockLockedTo) {
        StockDetailTo detailTo = stockLockedTo.getDetailTo();
        Long detailToId = detailTo.getId();
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailToId);

        if (byId != null) {
            Long taskId = stockLockedTo.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            R info = orderFeignService.getOrderInfoByOrderSn(orderSn);
            if (info.getCode() == 0) {
                OrderVo data = info.getData(new TypeReference<OrderVo>() {
                });
                Integer status = data.getStatus();
                if (data == null || status == OrderStatusEnum.CANCLED.getCode()) {
                    releaseStock(detailTo);
                }
            } else {
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getWareOrderTaskByOrderSn(orderSn);

        if (orderTaskEntity.getTaskStatus() == 1) {
            Long id = orderTaskEntity.getId();
            List<WareOrderTaskDetailEntity> taskDetailList = wareOrderTaskDetailService.getTaskDetailByTaskId(id);
            List<WareOrderTaskDetailEntity> collect = taskDetailList.stream().filter(item -> item.getLockStatus() == 1).collect(Collectors.toList());
            collect.stream().forEach(item -> {
                wareSkuDao.releaseStock(item.getSkuId(), item.getWareId(), item.getSkuNum());
            });
        }

    }

    /**
     * 订单取消，补回商品库存
     *
     * @param locked
     */
    private void releaseStock(StockDetailTo locked) {
        Long skuId = locked.getSkuId();
        Long wareId = locked.getWareId();
        Integer skuNum = locked.getSkuNum();
        Long taskId = locked.getTaskId();
        wareSkuDao.releaseStock(skuId, wareId, skuNum);
        wareOrderTaskDetailService.changeLockStatus(WareConstant.OrderTaskDetailStatusEnum.UNLOCK.getCode(), skuId, wareId, taskId);
    }

}